<template>
    <el-dialog :model-value="props.visible" title="订单详情" width="50%" @close="handleClose">
        <div id="pdf-content" ref="printArea">
            <table class="order-table">
                <colgroup>
                    <col style="width: 16.67%;">
                    <col style="width: 16.67%;">
                    <col style="width: 16.67%;">
                    <col style="width: 16.67%;">
                    <col style="width: 16.67%;">
                    <col style="width: 16.67%;">
                </colgroup>
                <caption>
                    <h3>生产工单</h3>
                </caption>
                <tr class="img-col">
                    <td colspan="6">
                        <img class="product-image" :src="detail?.renderingsUrl" alt="">
                    </td>
                </tr>
                <tr>
                    <td class="field-title">生产单备注</td>
                    <td colspan="5" class="not-center" >{{ detail?.produceOrderRemark }}</td>
                </tr>
                <tr>
                    <td class="field-title">BOM备注</td>
                    <td colspan="5" class="not-center" >{{ detail?.bomRemark }}</td>
                </tr>
                <tr>
                    <td class="field-title">产品名称</td>
                    <td colspan="2">{{ detail?.bomName }}</td>
                    <td class="field-title">制单日期</td>
                    <td colspan="2">{{ detail?.createTime }}</td>
                </tr>
                <tr>
                    <td class="field-title">需求总数</td>
                    <td colspan="2">{{ detail?.produceNumber }}</td>
                    <td class="field-title">交货日期</td>
                    <td colspan="2">{{ detail?.deliveryDate }}</td>
                </tr>
                <tr>
                    <td class="field-title">外箱名称</td>
                    <td colspan="2">{{ detail?.paperBoxName }}</td>
                    <td class="field-title">箱规</td>
                    <td colspan="2">{{ detail?.boxGauge }}</td>
                </tr>
                <tr>
                    <td class="field-title">生产单号</td>
                    <td colspan="5" class="img-col">
                        <img class="code-image" :src="detail?.codeUrl" alt="">
                        <div class="order-number">{{ detail?.produceOrderCode }}</div>
                    </td>
                </tr>
                <tr>
                    <td class="field-title">包装方式</td>
                    <td colspan="2">{{ detail?.packingMethod || '无' }}</td>
                    <td colspan="1" class="field-title">包装工费</td>
                    <td colspan="2">{{ packageCost }}</td>
                </tr>
                <tr>
                    <td class="field-title">组装工费</td>
                    <td colspan="5">{{ assembleCost }}</td>
                </tr>
                <tr>
                    <td colspan="4" class="field-title">部件名称</td>
                    <td colspan="1" class="field-title">单品数量</td>
                    <td colspan="1" class="field-title">需求总数</td>
                </tr>
                <tr v-if="detail?.semiList">
                    <td class="field-title" colspan="1" :rowspan="detail?.semiList.length + 1">半成品</td>
                </tr>
                <tr v-for="(item,index) in detail?.semiList" :key="index + 1">
                    <td colspan="3" >
                        <div class="auxiliary-name">
                            <span class="product-name">{{ item?.productName }}</span>
                            <span :class="item?.inventoryNumber < item?.needTotal? 'inventory-alert':' '" >{{ `库存数量:${item?.inventoryNumber}`}}</span>
                        </div>
                    </td>
                    <td colspan="1">{{ item?.proportionNumber }}</td>
                    <td colspan="1">{{ item?.needTotal }}</td>
                </tr>
                <tr v-if="detail?.packingList">
                    <td class="field-title" colspan="1" :rowspan="detail?.packingList.length + 1">包装件</td>
                </tr>
                <tr v-for="(item,index) in detail?.packingList" :key="index + 1">
                    <td colspan="3">
                        <div class="auxiliary-name">
                            <span class="product-name">{{ item?.productName }}</span>
                            <span :class="item?.inventoryNumber < item?.needTotal? 'inventory-alert':' '" >{{ `库存数量:${item?.inventoryNumber}`}}</span>
                        </div>
                    </td>
                    <td colspan="1">{{ item?.proportionNumber }}</td>
                    <td colspan="1">{{ item?.needTotal }}</td>
                </tr>
                <tr v-if="detail?.auxiliaryList">
                    <td class="field-title" colspan="1" :rowspan="detail?.auxiliaryList.length + 1">通用部件(辅材)</td>
                </tr>
                <tr v-for="(item,index) in detail?.auxiliaryList" :key="index + 1">
                    <td colspan="3">
                        <div class="auxiliary-name">
                            <span class="product-name">{{ item?.productName }}</span>
                            <span :class="item?.inventoryNumber < item?.needTotal? 'inventory-alert':' '">{{ `库存数量:${item?.inventoryNumber}`}}</span>
                        </div>
                    </td>
                    <td colspan="1">{{ item?.proportionNumber }}</td>
                    <td >{{ item?.needTotal }}</td>
                </tr>
                <tr>
                    <td colspan="6" class="field-title">包装人员信息</td>
                </tr>
                <tr>
                    <td class="field-title">工号</td>
                    <td v-for="(item, index) in new Array(5)" :key="index + 1"></td>
                </tr>
                <tr>
                    <td class="field-title">组装数量</td>
                    <td v-for="(item, index) in new Array(5)" :key="index + 1"></td>
                </tr>
                <tr>
                    <td class="field-title">包装数量</td>
                    <td v-for="(item, index) in new Array(5)" :key="index + 1"></td>
                </tr>
                <tr>
                    <td class="field-title">验收总数</td>
                    <td colspan="5"></td>
                </tr>
            </table>
            <div class="order-info">
                <el-row>
                    <el-col :span="12">
                        {{`产品大类：${detail?.majorName}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`打印次数：${detail?.printCount}`}}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        {{`产品小类：${detail?.subclassName}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`制单人：${detail?.createByName}`}}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        {{`订单数量：${detail?.produceNumber}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`制单时间：${detail?.createTime}`}}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        {{`箱规：${detail?.boxGauge}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`交货日期：${detail?.deliveryDate}`}}
                    </el-col>
                </el-row>
            </div>
        </div>
        <!-- <div class="order-info-container">
            <div class="order-info">
                <el-row>
                    <el-col :span="12">
                        {{`产品大类：${detail?.majorName}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`打印次数：${detail?.printCount}`}}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        {{`产品小类：${detail?.subclassName}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`制单人：${detail?.createByName}`}}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        {{`订单数量：${detail?.produceNumber}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`制单时间：${detail?.createTime}`}}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        {{`箱规：${detail?.boxGauge}`}}
                    </el-col>
                    <el-col style="text-align: right" :span="12">
                        {{`交货日期：${detail?.deliveryDate}`}}
                    </el-col>
                </el-row>
            </div>
        </div> -->
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" :disabled="!shouldPrint" size="large" @click="onClickPrint" >打印</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">

import { printOrderDetailApi } from '@/api/sj/productManagement/BOMProductOrder';
import { jsPDF } from "jspdf";
import html2canvas from "html2canvas";

const props = defineProps<{
    visible: boolean;
    data?: any,
    packageMethod: any[]
}>();
const emits = defineEmits(['close']);
const detail = ref<any>();
const packageCost = ref(0);
const assembleCost = ref(0);

const shouldPrint = ref(false);
const printArea = ref<HTMLElement | null>(null);

watch(()=>props.data,(newData)=>{
    detail.value = newData;
    // 组装工费
    const assembleData = newData.laborCostVoList.filter((item: any)=> item.type == 1)[0];
    assembleCost.value = assembleData.price || 0;
    // 包装工费
    const packingData = newData.laborCostVoList.filter((item: any)=> item.type == 2)[0];
    packageCost.value = packingData.price;
    let semiListPass = true;
    let packageListPass = true;
    let auxiliaryListPass = true;
    //检查半成品
    if(newData.semiList){
        for(let semi of newData.semiList){
            if(semi.inventoryNumber < semi.needTotal ){
                semiListPass = false;
                break;
            };
        };
    };
    // 检查包装件
    if(newData.packingList){
        for(let packageItem of newData.packingList){
            if(packageItem.inventoryNumber < packageItem.needTotal ){
                packageListPass = false;
                break;
            };
        };
    };
    // 检查辅材
    if(newData.auxiliaryList){
        for(let auxiliary of newData.auxiliaryList){
            if(auxiliary.inventoryNumber < auxiliary.needTotal ){
                auxiliaryListPass = false;
                break;
            };
        };
    };
    shouldPrint.value = semiListPass && packageListPass && auxiliaryListPass;
},{deep: true});

const generatePDF = async () => {
    const element = document.getElementById("pdf-content");
    // const element = document.querySelector('#order-table');
    if (element) {
        // A4 页面宽度和高度（单位：毫米）
        const pdfWidth = 210;
        const pdfHeight = 297;
        const canvas = await html2canvas(element,{ useCORS: true, scale: 2 });
        const imgData = canvas.toDataURL("image/jpeg", 0.98);
        // 计算内容的实际比例
        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        const pageHeight = (contentHeight * pdfWidth) / contentWidth;
        let position = 0;
        const pdf = new jsPDF({
            orientation: "portrait",
            unit: "mm",
            format: "a4"
        });
        // 判断内容是否需要分页
        if (pageHeight < pdfHeight) {
            pdf.addImage(imgData, "JPEG", 0, 0, pdfWidth, pageHeight);
        } else {
            while (position < contentHeight) {
                pdf.addImage(imgData, "JPEG", 0, position, pdfWidth, pageHeight);
                position -= pdfHeight;
                if (position < contentHeight) {
                    pdf.addPage();
                };
            };
        };
        const pdfBlob = pdf.output("blob");
        // pdfUrl.value = URL.createObjectURL(pdfBlob); 
        pdf.save("document.pdf");
    };
};

const onClickPrint = async () => {
    if(printArea.value){
        // 保存当前页面的原始内容
        const originalContent = document.body.innerHTML
        // 获取要打印的内容
        const printContent = printArea.value.innerHTML

        // 替换页面内容为要打印的内容
        document.body.innerHTML = printContent

        // 调用打印
        window.print()

        // 打印后恢复原始内容
        document.body.innerHTML = originalContent
        // location.reload() // 可选：刷新页面以恢复事件监听
    };
    await printOrderDetailApi({id: detail.value.id});
};

const handleClose = () => {
    emits('close');
};

</script>

<style lang="scss" scoped>
#pdf-content{
    display: flex;
    justify-content: center;
    flex-flow:wrap

}
.order-table{
    border-spacing: 0;
    border: 1px solid black;
    width: 90%;
    font-size: 20px;
    tr{
        border: 1px solid black;
    }
    td{
        border: 1px solid black;
        text-align: center;
    }
    .img-col{
        text-align: center;
        .product-image{
            height: 250px;
        }
        .order-numbe{
            color: blue
        }
    }
    .not-center{
        text-align: left;
    }
    .code-image{
        height: 100px
    }
    .inventory-alert{
        color: red;
    }
    .field-title{
        font-weight: bold;
    }
    .auxiliary-name{
        color: #69AFF0;
        text-align: left;
        span{
            display: block
        }
        font-size: 20px;
    }
    
}
.order-info{
    margin-top:20px;
    width: 90%;
    font-size: 15px;
}

// .order-info-container{
//     margin-top:20px;
//     display: flex;
//     justify-content: center;
//     font-size: 20px;
//     .order-info{
//         width: 80%;
//     }
// }
</style>